package Servlet.Filter;


import Table.Manager;
import Table.User;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

@WebFilter("/*")
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //强制转换
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //获取资源请求路径
        String uri = request.getRequestURI();
        //判断是否包含登录需要的资源路径,排除验证码
        if (uri.contains("/Login.html") || uri.contains("/loginServlet") || uri.contains("/checkCode") || uri.contains("/loginErrorServlet")) {
            //包含,用户像登录，放行
            filterChain.doFilter(servletRequest, servletResponse);
        } else {
            //不包含，需要验证用户是否登录过
            User user = (User) request.getSession().getAttribute("user");
            Manager manager = (Manager) request.getSession().getAttribute("manager");
            if (user != null || manager != null) {
                //说明用户在session注销之前登录过
                filterChain.doFilter(servletRequest, servletResponse);
            } else {
                request.getSession().setAttribute("error", "你尚为登录过，请登录!");
                response.sendRedirect("/Book_Web/Login.html");
            }
        }
    }

    @Override
    public void destroy() {

    }
}
